'use client';

import { Button, Form, Input, Modal, Popconfirm, Space, TreeSelect, InputNumber, Switch, message } from 'antd';
import { useRequest } from 'ahooks';
import dayjs from 'dayjs';
import { useRef, useState } from 'react';
import ImageUpload from '@/components/ImageUpload';
import { getMenuList, createMenu, updateMenu, deleteMenu, getMenuPage } from '@/apis/admin/menu';
import { Menu } from '@/types/menu';
import { ActionType, ProColumns, ProTable } from '@ant-design/pro-components';

const MenusPage = () => {
  const [form] = Form.useForm();
  const actionRef = useRef<ActionType>(null);

  const [isOpen, setIsOpen] = useState(false);
  const [editId, setEditId] = useState<string | null>(null);

  const { data: menuTree } = useRequest(() => getMenuList({}));

  const handleEdit = (record: Menu) => {
    setIsOpen(true);
    setEditId(record.id);
    form.setFieldsValue(record);
  };

  const handleOk = async () => {
    try {
      const values = await form.validateFields();
      const payload = {
        ...values,
        name: values.name || '',
        iconFileId: values.iconFile?.id || '',
        parentId: values.parentId || '',
        order: Number(values.order || 0),
        isActive: values.isActive ? 1 : 0,
      };
      if (editId) {
        await updateMenu({ id: editId, ...payload });
        message.success('更新成功');
      } else {
        await createMenu(payload);
        message.success('创建成功');
      }
      setIsOpen(false);
      actionRef.current?.reload();
    } catch (error) {
      console.error(error);
    }
  };

  const handleDelete = async (id: string) => {
    try {
      await deleteMenu({ id });
      message.success('删除成功');
      actionRef.current?.reload();
    } catch (error) {
      console.error(error);
    }
  };

  const columns: ProColumns<Menu>[] = [
    {
      title: 'ID',
      dataIndex: 'id',
      search: false,
    },
    {
      title: '名称',
      dataIndex: 'name',
    },
    {
      title: '系统编码',
      dataIndex: 'sysCode',
    },
    {
      title: '图标',
      dataIndex: 'iconFile',
      render: (_, record) => <img src={record.iconFile?.url} alt="icon" style={{ width: 30 }} />,
      search: false,
    },
    {
      title: '创建时间',
      dataIndex: 'createdAt',
      valueType: 'dateTime',
      search: false,
    },
    {
      title: '更新时间',
      dataIndex: 'updatedAt',
      valueType: 'dateTime',
      search: false,
    },
    {
      title: '操作',
      key: 'action',
      search: false,
      render: (_: any, record: Menu) => (
        <Space size="middle">
          <a onClick={() => handleEdit(record)}>编辑</a>
          <Popconfirm title="确定删除吗？" onConfirm={() => handleDelete(record.id)}>
            <a>删除</a>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  return (
    <div>
      <ProTable<Menu>
        columns={columns}
        actionRef={actionRef}
        request={async (params) => {
          const { data, total } = await getMenuPage({ current: params.current, pageSize: params.pageSize, name: params.name });
          return { data: data, total };
        }}
        rowKey="id"
        search={{
          labelWidth: 'auto',
        }}
        toolBarRender={() => [
          <Button
            type="primary"
            onClick={() => {
              setIsOpen(true);
              setEditId(null);
              form.resetFields();
            }}
          >
            新增
          </Button>,
        ]}
      />
      <Modal title={editId ? '编辑' : '新增'} open={isOpen} onOk={handleOk} onCancel={() => setIsOpen(false)}>
        <Form form={form} layout="vertical">
          <Form.Item label="名称" name="name" rules={[{ required: true }]}>
            <Input />
          </Form.Item>
          <Form.Item label="父级菜单" name="parentId">
            <TreeSelect treeData={menuTree} fieldNames={{ label: 'name', value: 'id' }} treeDefaultExpandAll />
          </Form.Item>
          <Form.Item label="路径" name="path" rules={[{ required: true }]}>
            <Input />
          </Form.Item>
          <Form.Item label="排序" name="order">
            <InputNumber />
          </Form.Item>
          <Form.Item label="是否激活" name="isActive" valuePropName="checked">
            <Switch />
          </Form.Item>
          <Form.Item label="图标" name="iconFile" rules={[{ required: true }]}>
            <ImageUpload />
          </Form.Item>
          <Form.Item label="系统编码" name="sysCode">
            <Input />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default MenusPage;